package com.example.springsecurityextraloginfield.controller;

import com.example.springsecurityextraloginfield.entity.UserDAO;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@Controller
public class WebController {

    @GetMapping(value = "/")
    public String root(){
        return "redirect:/index";
    }

    @GetMapping(value = "/index",produces = MediaType.APPLICATION_JSON_VALUE)
    public String index(Model model){
        getDomain().ifPresent(s ->{
            model.addAttribute("domain",s);
        });
        return "index";
    }

    @GetMapping(value = "/user/index",produces = MediaType.APPLICATION_JSON_VALUE)
    public String userIndex(Model model){
        getDomain().ifPresent(s ->{
            model.addAttribute("domain",s);
        });
        return "user/index";
    }

    @RequestMapping(value = "/login")
    public String login(){
        return "login";
    }
    private Optional<String> getDomain(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String domain = "";
        if (authentication != null && !authentication.getClass().equals(AnonymousAuthenticationToken.class)) {
            UserDAO userDAO = (UserDAO) authentication.getPrincipal();
            domain = userDAO.getDomain();
        }
        return Optional.ofNullable(domain);
    }
}
